package com.ljh.aiplatform.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ljh.aiplatform.annotation.AuthCheck;
import com.ljh.aiplatform.common.BaseResponse;
import com.ljh.aiplatform.common.DeleteRequest;
import com.ljh.aiplatform.common.ErrorCode;
import com.ljh.aiplatform.common.ResultUtils;
import com.ljh.aiplatform.config.AdminSchedulerConfig;
import com.ljh.aiplatform.constant.UserConstant;
import com.ljh.aiplatform.exception.BusinessException;
import com.ljh.aiplatform.exception.ThrowUtils;
import com.ljh.aiplatform.manager.AiManager;
import com.ljh.aiplatform.manager.RedisLimitManager;
import com.ljh.aiplatform.model.dto.ai.AiGenerateQuestionRequest;
import com.ljh.aiplatform.model.dto.question.*;
import com.ljh.aiplatform.model.entity.App;
import com.ljh.aiplatform.model.entity.Question;
import com.ljh.aiplatform.model.entity.User;
import com.ljh.aiplatform.model.enums.AppTypeEnum;
import com.ljh.aiplatform.model.vo.QuestionVO;
import com.ljh.aiplatform.service.AppService;
import com.ljh.aiplatform.service.QuestionService;
import com.ljh.aiplatform.service.UserService;
import com.zhipu.oapi.service.v4.model.ChatMessage;
import com.zhipu.oapi.service.v4.model.ChatMessageRole;
import com.zhipu.oapi.service.v4.model.ModelData;
import io.reactivex.Flowable;
import io.reactivex.Scheduler;
import io.reactivex.schedulers.Schedulers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 问题接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@RestController
@RequestMapping("/question")
@Slf4j
public class QuestionController {

    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;

    @Resource
    private AppService appService;

    @Resource
    private AiManager aiManager;
    @Resource
    private Scheduler adminScheduler;

    @Resource
    private RedisLimitManager redisLimitManager;

    List<ChatMessage> chatMessageList = new ArrayList<>();

    // region 增删改查

    /**
     * 创建问题
     *
     * @param questionAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addQuestion(@RequestBody QuestionAddRequest questionAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(questionAddRequest == null, ErrorCode.PARAMS_ERROR);
        // 在此处将实体类和 DTO 进行转换
        //接收前端参数的时候用封装类结构清晰
        Question question = new Question();
        BeanUtils.copyProperties(questionAddRequest, question);
        List<QuestionContentDTO> questionContent = questionAddRequest.getQuestionContent();
        question.setQuestionContent(JSONUtil.toJsonStr(questionContent));
        // 数据校验
        questionService.validQuestion(question, true);
        // 填充默认值
        User loginUser = userService.getLoginUser(request);
        question.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = questionService.save(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newQuestionId = question.getId();
        return ResultUtils.success(newQuestionId);
    }

    /**
     * 删除问题
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldQuestion.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = questionService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新问题（仅管理员可用）
     *
     * @param questionUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestion(@RequestBody QuestionUpdateRequest questionUpdateRequest) {
        if (questionUpdateRequest == null || questionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        Question question = new Question();
        BeanUtils.copyProperties(questionUpdateRequest, question);
        List<QuestionContentDTO> questionContent = questionUpdateRequest.getQuestionContent();
        question.setQuestionContent(JSONUtil.toJsonStr(questionContent));
        // 数据校验
        questionService.validQuestion(question, false);
        // 判断这个题目对应的app是否存在
        Long appId = questionUpdateRequest.getId();
        final App app = appService.getById(appId);
        ThrowUtils.throwIf(app == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        LambdaUpdateWrapper<Question> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Question::getAppId, appId)
                .set(Question::getQuestionContent, question.getQuestionContent());
        boolean result = questionService.update(lambdaUpdateWrapper);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取问题（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<QuestionVO> getQuestionVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Question question = questionService.getById(id);
        ThrowUtils.throwIf(question == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(questionService.getQuestionVO(question, request));
    }

    /**
     * 分页获取问题列表（仅管理员可用）
     *
     * @param questionQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Question>> listQuestionByPage(@RequestBody QuestionQueryRequest questionQueryRequest) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 查询数据库
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        return ResultUtils.success(questionPage);
    }

    /**
     * 分页获取问题列表（封装类）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                               HttpServletRequest request) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        // 获取封装类
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }

    /**
     * 分页获取当前登录用户创建的问题列表
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listMyQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(questionQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        questionQueryRequest.setUserId(loginUser.getId());
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        // 获取封装类
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }

    /**
     * 编辑问题（给用户使用）
     *
     * @param questionEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editQuestion(@RequestBody QuestionEditRequest questionEditRequest, HttpServletRequest request) {
        if (questionEditRequest == null || questionEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        Question question = new Question();
        BeanUtils.copyProperties(questionEditRequest, question);
        List<QuestionContentDTO> questionContent = questionEditRequest.getQuestionContent();
        question.setQuestionContent(JSONUtil.toJsonStr(questionContent));
        // 数据校验
        questionService.validQuestion(question, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = questionEditRequest.getId();
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldQuestion.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = questionService.updateById(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion


    private static final String SystemPromptQuestion = "你是一位严谨的出题专家，我会给你如下信息：\n" +
            "```\n" +
            "应用名称，\n" +
            "【【【应用描述】】】，\n" +
            "应用类别，\n" +
            "要生成的题目数，\n" +
            "每个题目的选项数\n" +
            "```\n" +
            "\n" +
            "请你根据上述信息，按照以下步骤来出题：\n" +
            "1. 要求：题目和选项尽可能地短，题目不要包含序号，每题的选项数以我提供的为主，题目不能重复\n" +
            "2. 严格按照下面的 json 格式输出题目和选项\n" +
            "```\n" +
            "[{\"options\":[{\"value\":\"选项内容\",\"key\":\"A\"},{\"value\":\"\",\"key\":\"B\"}],\"title\":\"题目标题\"}]\n" +
            "```\n" +
            "title 是题目，options 是选项，每个选项的 key 按照英文字母序（比如 A、B、C、D）以此类推，value 是选项内容\n" +
            "3. 检查题目是否包含序号，若包含序号则去除序号\n" +
            "4. 返回的题目列表格式必须为 JSON 数组\n";

    /**
     * 封装用户的prompt
     *
     * @param app
     * @param questionsNum
     * @param optionsNum
     * @return
     */
    public String getUserPrompt(App app, Integer questionsNum, Integer optionsNum) {
        ThrowUtils.throwIf(app == null, ErrorCode.NOT_FOUND_ERROR, "应用不存在");
        StringBuilder userPrompt = new StringBuilder();
        userPrompt.append("应用名称" + app.getAppName()).append("\n");
        userPrompt.append("应用描述" + app.getAppDesc()).append("\n");
        userPrompt.append("应用类别" + AppTypeEnum.getEnumByValue(app.getAppType()).getText()).append("\n");
        userPrompt.append(questionsNum).append("\n");
        userPrompt.append(optionsNum);
        return userPrompt.toString();
    }

    /**
     * AI生成题目（非流式）
     *
     * @param aiGenerateQuestionRequest
     * @return
     */
    @PostMapping("/ai_generate")
    public BaseResponse<List<QuestionContentDTO>> aiGenerateQuestion(@RequestBody AiGenerateQuestionRequest aiGenerateQuestionRequest) {
        ThrowUtils.throwIf(aiGenerateQuestionRequest == null, ErrorCode.PARAMS_ERROR, "ai参数为空");
        Long appId = aiGenerateQuestionRequest.getAppId();
        App app = appService.getById(appId);
        ThrowUtils.throwIf(app == null, ErrorCode.NOT_FOUND_ERROR, "应用不存在");
        Integer questionsNum = aiGenerateQuestionRequest.getQuestionsNum();
        Integer optionsNum = aiGenerateQuestionRequest.getOptionsNum();
        String userPrompt = getUserPrompt(app, questionsNum, optionsNum);
        chatMessageList.add(new ChatMessage(ChatMessageRole.SYSTEM.value(), SystemPromptQuestion));
        chatMessageList.add(new ChatMessage(ChatMessageRole.USER.value(), userPrompt));
        String result = aiManager.doRequest(chatMessageList, Boolean.FALSE, null);
        System.out.println(result);
        int startIndex = result.indexOf("[");
        int endIndex = result.lastIndexOf("]");
        String jsonStr = result.substring(startIndex, endIndex + 1);
        chatMessageList.add(new ChatMessage(ChatMessageRole.ASSISTANT.value(), jsonStr));
        List<QuestionContentDTO> questionContentDTOS = JSONUtil.toList(jsonStr, QuestionContentDTO.class);
        return ResultUtils.success(questionContentDTOS);
    }

    /**
     * AI生成题目（流式）
     * +
     *
     * @param aiGenerateQuestionRequest
     * @return
     */
    @GetMapping("/ai_generate/sse")
    public SseEmitter aiGenerateQuestionSSE(AiGenerateQuestionRequest aiGenerateQuestionRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(aiGenerateQuestionRequest == null, ErrorCode.PARAMS_ERROR, "ai参数为空");
        Long appId = aiGenerateQuestionRequest.getAppId();
        App app = appService.getById(appId);
        ThrowUtils.throwIf(app == null, ErrorCode.NOT_FOUND_ERROR, "应用不存在");
        Integer questionsNum = aiGenerateQuestionRequest.getQuestionsNum();
        Integer optionsNum = aiGenerateQuestionRequest.getOptionsNum();
        String userPrompt = getUserPrompt(app, questionsNum, optionsNum);
        User loginUser = userService.getLoginUser(request);
        //做限流处理 ： 每秒钟最多请求两次
        String key = "aiGenerateQuestionSSE" + loginUser.getId();
        redisLimitManager.doRateLimit(key);
        //调用Ai接口
        Flowable<ModelData> modelDataFlowable = aiManager.doStreamRequest(SystemPromptQuestion, userPrompt, null);
        AtomicInteger count = new AtomicInteger();//用AtomicInteger可以保证线程安全（因为在使用流的时候，其实是个多线程的环境，普通的int无法保证线程安全）
        SseEmitter sseEmitter = new SseEmitter();
        StringBuilder stringBuilder = new StringBuilder();
        Scheduler scheduler = Schedulers.single();
        final String userRole = loginUser.getUserRole();
        if (userRole.equals("admin")) {
            scheduler = adminScheduler;
        }
        modelDataFlowable.observeOn(Schedulers.io())
                .map(modelData -> modelData.getChoices().get(0).getDelta().getContent())
                .map(modelData -> modelData.replaceAll("\\s", ""))//\\s 是一个正则表达式，表示匹配任意空白字符。 replaceAll("\\s", "") 这行代码用于去除字符串中的所有空白字符，包括空格、制表符(Tab)、换行符和其他空白字符
                .filter(StringUtils::isNotBlank)
                .flatMap(message -> {
                    List<Character> characterList = new ArrayList<>();
                    for (char c : message.toCharArray()) {
                        characterList.add(c);
                    }
                    return Flowable.fromIterable(characterList);
                })//latMap 是 ReactiveX（RxJava）库中的一个非常重要且常用的操作符。它的作用是将源 Observable 或 Flowable 发送的每个数据项映射为一个新的 Observable 或 Flowable
                .doOnNext(character -> {
                    if (character.equals('{')) {
                        count.addAndGet(1);
                    }
                    if (count.get() > 0) {
                        stringBuilder.append(character);
                    }
                    if (character.equals('}')) {
                        count.addAndGet(-1);
                        if (count.get() == 0) {
                            System.out.println("当前线程的名称" + Thread.currentThread().getName());
                            if (userRole.equals("user")) {
                                Thread.sleep(10000L);
                            }
                            sseEmitter.send(JSONUtil.toJsonStr(stringBuilder.toString()));
                            stringBuilder.setLength(0);
                        }
                    }
                })
                .doOnError(throwable -> sseEmitter.completeWithError(throwable))
                .doOnComplete(sseEmitter::complete)
                .observeOn(scheduler)
                .subscribe();
        return sseEmitter;

    }
}
